package com.home.base.util;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebClientOptions;
import com.gargoylesoftware.htmlunit.html.*;
import com.home.base.constant.GlobalConstant;
import com.home.biz.JobLogBiz;
import com.home.biz.JobUserBiz;
import com.home.config.InitDataConfig;
import com.home.entity.JobLog;
import com.home.entity.JobUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;

/**
 * @author ：chenxf
 * @date ：Created in 2019/6/17 15:52
 * @description：
 * @modified By：
 * @version: $
 */
@Slf4j

public class WebClientUtil {
    private JobLogBiz jobLogBiz;
    private JobUserBiz jobUserBiz;
    private WebClient webClient = new WebClient(BrowserVersion.CHROME);


    public  WebClientUtil(JobLogBiz jobLogBiz,JobUserBiz jobUserBiz){
        this.jobLogBiz=jobLogBiz;
        this.jobUserBiz=jobUserBiz;
        WebClientOptions clientOptions = webClient.getOptions();
        // 设置webClient的相关参数
        clientOptions.setJavaScriptEnabled(false);
        clientOptions.setCssEnabled(false);
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());
        clientOptions.setTimeout(35000);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        clientOptions.setThrowExceptionOnScriptError(false);
    }

    public void close() {
        webClient.close();
    }

    public boolean shopList() throws Exception{

            webClient.getCache().clear();
            if(StringUtils.isBlank(InitDataConfig.jobConfig.getFetchUrl())){
                //停止任务
                InitDataConfig.jobConfig.setDelFlg(1);
                jobLogBiz.insertSelective(JobLog.builder().notes("采集地址为空，停止采集任务").build());
                return false;
            }
            jobLogBiz.insertSelective(JobLog.builder().notes("开始采集").build());
            log.info(" 购买开始");
            HtmlPage htmlPage=webClient.getPage(InitDataConfig.jobConfig.getFetchUrl());
            HtmlElement ulHtml=htmlPage.querySelector(".product-listing");
        //ulHtml.querySelector("li")
            List<HtmlButton> buttons=htmlPage.getByXPath("//button");

        List<HtmlElement> titleElements= htmlPage.getByXPath("//a/dl/dt");
        for(HtmlElement titleElement:titleElements){
            String title=titleElement.getAttribute("title");

            if(StringUtils.isBlank(InitDataConfig.jobConfig.getFilter())|| title.indexOf(InitDataConfig.jobConfig.getFilter())==-1){
                HtmlElement buttonDiv= titleElement.getParentNode().getParentNode().getParentNode().querySelector(".product-action");
                HtmlButton button= buttonDiv.querySelector("button");
                if(button!=null){
                    String  buttonText=button.getTextContent();
                    if(buttonText.trim().equals("カートに入れる")){
                        return cartPage(button.click());
                    }
                }


            }
        }

//        for(HtmlButton button:buttons){
//               String  buttonText=button.getTextContent();
//                if(buttonText.trim().equals("カートに入れる")){
//
//                   DomNode liHtml= button.getParentNode().getParentNode().getParentNode();//.getParentNode();
//
//
//                    return cartPage(button.click());
//                }
//            }

            return false;


    }

    public boolean cartPage(HtmlPage cartPage) throws Exception{

        log.info(" 加入购物车");
        List<HtmlButton> buttons=cartPage.getByXPath("//button");
        for(HtmlButton button:buttons){
            String  buttonText=button.getTextContent();
            if(buttonText.trim().equals("予約の手続きに進む")){
               return orderPage(button.click());
                //break;
            }
        }
        return false;
    }

    public boolean orderPage(HtmlPage page) throws Exception{
            log.info(" 填写订单信息");
            HtmlForm form;

            for(HtmlForm temp:page.getForms()){
                form=temp;
                if("/checkout/update/address".equals( temp.getActionAttribute())){
                    LocalDate startDate=DateUtil.getLocalDate(form.getInputByName("depart_term_available_on").getValueAttribute(),"/"),
                     endDate=DateUtil.getLocalDate(form.getInputByName("depart_term_disavailable_on").getValueAttribute(),"/");
                    List<JobUser> jobUsers=jobUserBiz.corroctUsers(DateUtil.getByLocalDate(startDate),DateUtil.getByLocalDate(endDate));
                    if(jobUsers.size()==0){
                        jobLogBiz.insertSelective(JobLog.builder().notes(startDate.toString()+"-"+endDate.toString()+"无可用乘客信息,采集失败").build());

                        return false;
                    }
                    JobUser jobUser=jobUsers.get(0);
                    form.getInputByName("order[bill_address_attributes][fullname]").setValueAttribute(jobUser.getName());
                    form.getInputByName("order[email]").setValueAttribute(jobUser.getEmail());
                    form.getInputByName("order[email_confirmation]").setValueAttribute(jobUser.getEmail());
                    form.getSelectByName("order[life_locale]").getOptionByValue("china_locale").click();
                                       // page.getElementById("radio-other").click();

                    form.getSelectByName("order[required_nationality]").getOptionByValue("china").click();

                    form.getInputByName("order[bill_address_attributes][phone_country]").setValueAttribute("86");
                    form.getInputByName("order[bill_address_attributes][phone]").setValueAttribute(jobUser.getPhone());


                    LocalDate date=DateUtil.getLocalDateByDate(jobUser.getDepartTime());

                    form.getSelectByName("order[depart_on(1i)]").getOptionByValue(date.getYear()+"").click();
                    form.getSelectByName("order[depart_on(2i)]").getOptionByValue(date.getMonthValue()+"").click();
                    form.getSelectByName("order[depart_on(3i)]").getOptionByValue(date.getDayOfMonth()+"").click();
                    int week=date.getDayOfWeek().getValue();
                    if(week==7){
                        week=0;
                    }
                    form.getSelectByName("order[depart_day_of_the_week]").getOptionByValue(week+"").click();
                    List<HtmlSelect> selects=form.getSelectsByName("order[airline_ids][]");
                    for(HtmlSelect select:selects){
                        try {
                            select.getOptionByValue(jobUser.getAirline()).click();
                        }catch (Exception e){
                            continue;
                        }
                    }

                    form.getInputByName("order[flight_number]").setValueAttribute(jobUser.getFlightNumber());
                    form.getSelectByName("order[destination_region_id]").getOptionByValue("4").click();
                    form.getInputByName("order[destination_city]").setValueAttribute(jobUser.getDestinationCity());


                    HtmlButton button=form.getButtonByName("checkout");

                    return confirm( button.click(),jobUser);

                }

            }
            return false;


    }

    public boolean confirm(HtmlPage page,JobUser jobUser) throws Exception{
            HtmlForm form;
            for(HtmlForm temp:page.getForms()) {
                form = temp;
                if ("/checkout/update/confirm".equals(temp.getActionAttribute())) {

                    HtmlInput check = (HtmlInput)page.querySelector(".js-toggle_agree");
                    check.click();
                   // form.getInputByName("order[state_lock_version]").setValueAttribute("4");
                    HtmlButton button = form.getButtonByName("button");

                     button.click();
                    log.info(" 下单成功");
                    jobUserBiz.updateSelectiveById(JobUser.builder().id(jobUser.getId()).departTime(jobUser.getDepartTime()).status("1").build());
                    jobLogBiz.insertSelective(JobLog.builder().notes(jobUser.getName()+"email="+jobUser.getEmail()+"出发时间"+DateUtil.formatDate(jobUser.getDepartTime(),"yyyy-MM-dd")+"下单成功").build());
                    return true;
                }
            }
            return false;

    }

    public static void main(String[] args){
        try {
            System.out.println(new BigDecimal(-1).compareTo(BigDecimal.ZERO));
            if(BigDecimal.ZERO.compareTo(BigDecimal.ZERO)>0){

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
